package com.realtyManage.springboot.Service.impl;

import com.realtyManage.springboot.Config.MyLog;
import com.realtyManage.springboot.Dao.*;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Vo.BaseEntity;
import com.realtyManage.springboot.Model.Vo.SubordinateEntity;
import com.realtyManage.springboot.Service.CommodityService;
import com.realtyManage.springboot.Service.VikiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CommodityServiceImpl implements CommodityService {

    @Autowired
    private CommodityRepository commodityRepository;

    @Autowired
    private ExchangeRepository exchangeRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CouponRepository couponRepository;

    @Autowired
    private ExchangeCouponRepository exchangeCouponRepository;

    @Autowired
    private CouponDetailRepository couponDetailRepository;

    @Autowired
    private SingInRepository singInRepository;

    @Autowired
    private IntegralRepository integralRepository;   //积分Dao

    @Autowired
    private CustomerEvaluationRepository customerEvaluationRepository; //客户评论Dao

    @Autowired
    private ReceptionFabulousRepository receptionFabulousRepository;

    @Autowired
    private TintegralRepository tintegralRepository;

    @Autowired
    private CustomerRegistrationRepository customerRegistrationRepository;

    @Override
    public int addCommodity(Commodity commodity) {
        return commodityRepository.save(commodity).getId();
    }

    @Override
    public int deleteCommodity(List id) {
        return commodityRepository.deleteCommodity(id);
    }

    @Override
    public int updateCommodity(Commodity commodity) {
        return commodityRepository.updateCommodity(commodity);
    }

    @Override
    public Page<Commodity> findCommodity(BaseEntity baseEntity) {
        Integer pageNumber = baseEntity.getPageNumber() - 1;
        Integer pageSize = baseEntity.getPageSize();
        // 排序条件 默认最新
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if (baseEntity.getSort() != null) {
            if (baseEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, baseEntity.getSortField());
            } else if (baseEntity.getSort().equals("ASC")) {
                sort = new Sort(Sort.Direction.ASC, baseEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);
        //动态查询条件
        Specification<Commodity> specification = (Specification<Commodity>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page<Commodity> lst = commodityRepository.findAll(specification, pageable);
        return lst;
    }

    @Override
    public Page<Exchange> queryExchangeRecord(BaseEntity baseEntity) {
        Integer pageNumber = baseEntity.getPageNumber() - 1;
        Integer pageSize = baseEntity.getPageSize();
        // 排序条件 默认最新
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if (baseEntity.getSort() != null) {
            if (baseEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, baseEntity.getSortField());
            } else if (baseEntity.getSort().equals("ASC")) {
                sort = new Sort(Sort.Direction.ASC, baseEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);
        //动态查询条件
        Specification<Exchange> specification = (Specification<Exchange>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
                Predicate p0 = criteriaBuilder.equal(root.get("type"), 2);
                list.add(p0);
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page<Exchange> lst = exchangeRepository.findAll(specification, pageable);
        for (Exchange exchange : lst.getContent()) {
            exchange.setUserName(userRepository.queryUserName(exchange.getUserId().toString()));
        }
        return lst;
    }

    @Override
    public Commodity findCommodityById(String id) {
        return commodityRepository.findCommodityById(id);
    }

    @Override
    public List<Exchange> findExchangeList(String id) {
        return exchangeRepository.findExchangeList(id);
    }

    @Override
    public Exchange findExchangeById(String id) {
        return exchangeRepository.findById(id);
    }

    @Override
    public int exchangeCommodity(Exchange exchange) {
        return exchangeRepository.save(exchange).getId();
    }

    @Override
    public int transactionCommodity(Exchange exchange) {
         return exchangeRepository.updateExchange(exchange);
    }

    @Override
    public int backIntegral(Exchange exchange) {
        Integer code = 0;
        Commodity c = new Commodity();
        c.setId(exchange.getCommodityId());
        synchronized (this){
            Integer stock = commodityRepository.findNumById(exchange.getId());
            Integer zs = Integer.valueOf(exchange.getNum()) + stock;  //商品库存
            c.setNum(zs.toString());
            if (commodityRepository.updateCommodity(c) > 0){  //商品库存退还
                Integer ujf = userRepository.getIntegral(exchange.getUserId()); //获取用户积分
                Integer backIntegra = ujf + exchange.getIntegral();
                User user = new User();
                user.setId(exchange.getUserId());
                user.setIntegral(backIntegra);
                if (userRepository.updateUser(user) > 0){    //退还用户积分
                    code = 1;
                }
            }
        }
        return code;
    }

    @Override
    public int getUserIntegral(String id) {
        return userRepository.getIntegral(Integer.valueOf(id));
    }

    @Override
    public int insertWCoupon(Coupon coupon) {
        return couponRepository.save(coupon).getId();
    }

    @Override
    public boolean insertNCoupon(ExchangeCoupon exchangeCoupon) {
        ExchangeCoupon ec = exchangeCouponRepository.saveAndFlush(exchangeCoupon);
        if (ec.getId() > 0){
            return  true;
        }else{
            return  false;
        }
    }

    @Override
    public int deleteCoupon(List ids) {
        return couponRepository.deleteCoupon(ids);
    }

    @Override
    public int deleteExchangeCoupon(List ids) {
        return exchangeCouponRepository.deleteExchangeCoupon(ids);
    }

    @Override
    public List<ExchangeCoupon> getMyCoupon(String id,String phone) {
        return exchangeCouponRepository.findCouponByUserIdAndPhone(id,phone);
    }


    @Override
    public List<ExchangeCoupon> getMyDNCoupon(String id,String phone) {
        return exchangeCouponRepository.findDCouponByUserIdAndPhone(id,phone);
    }

    /*@Override
    public Page<ExchangeCoupon> findCouponAll(String content) {
        if (content != null){
            return exchangeCouponRepository.findAllByContent(content);
        }else{
            return exchangeCouponRepository.findAll();
        }
    }*/
    @MyLog(value = "查看优惠劵列表")
    @Override
    public Page<ExchangeCoupon> findPagedByWhereClause(String scanName,String userName,String houseCode, BaseEntity baseEntity) {
        Integer pageNumber = baseEntity.getPageNumber() - 1;
        Integer pageSize = baseEntity.getPageSize();
        // 排序条件 默认最新
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if (baseEntity.getSort() != null) {
            if (baseEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, baseEntity.getSortField());
            } else if (baseEntity.getSort().equals("ASC")) {
                sort = new Sort(Sort.Direction.ASC, baseEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);
        //动态查询条件
        Specification<ExchangeCoupon> specification = (Specification<ExchangeCoupon>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (scanName != null && scanName != "") {
                Predicate p0 = criteriaBuilder.like(root.get("scanName"), "%" + scanName + "%");
                list.add(p0);
            }
            if (userName != null && userName != "") {
                Predicate p1 = criteriaBuilder.like(root.get("userName"), "%" + userName + "%");
                list.add(p1);
            }
            if (houseCode != null && houseCode != "") {
                Predicate p2 = criteriaBuilder.like(root.get("houseCode"), "%" + houseCode + "%");
                list.add(p2);
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page<ExchangeCoupon> lst = exchangeCouponRepository.findAll(specification, pageable);
        //查询来访记录信息
        for (ExchangeCoupon exchangeCoupon : lst.getContent()) {
            exchangeCoupon.setUserName(userRepository.queryUserName(exchangeCoupon.getUserId()));
        }
        return lst;
    }

    @Override
    public ExchangeCoupon findCouponByIdDetail(String id) {
        return exchangeCouponRepository.findCouponByIdDetail(id);
    }

    @Override
    public int useCode(ExchangeCoupon exchangeCoupon) {
        return exchangeCouponRepository.update(exchangeCoupon);
    }

    @Override
    public Coupon findCouponByIdDetails(String id) {
        return couponRepository.findCouponByIdDetail(id);
    }

    @Override
    public int consumeCoupon(Coupon coupon) {
        return couponRepository.updateCoupon(coupon);
    }

    @Override
    public int exchangeCoupon(ExchangeCoupon exchangeCoupon) {
        return exchangeCouponRepository.save(exchangeCoupon).getId();
    }

    @Override
    public List<Coupon> queryWCoupon() {
        return couponRepository.queryWCoupon();
    }

    @Override
    public int purpose(ExchangeCoupon exchangeCoupon) {
        return exchangeCouponRepository.purpose(exchangeCoupon);
    }

    @Override
    public CouponDetail findCouponDetail() {
        return couponDetailRepository.findCouponDetail();
    }

    @Override
    public int updateCouponDetail(CouponDetail couponDetail) {
        return couponDetailRepository.saveAndFlush(couponDetail).getId();
    }

    @Override
    public int verificationCoupon(ExchangeCoupon exchangeCoupon) {
        return exchangeCouponRepository.purpose(exchangeCoupon);
    }

    @Override
    public int insertCustomerEvaluation(CustomerEvaluation customerEvaluation) {
        return customerEvaluationRepository.save(customerEvaluation).getId();
    }

    @Override
    public int fabulous(CustomerEvaluation customerEvaluation) {
        if (customerEvaluation.getType().equals("0")){
            return customerEvaluationRepository.save(customerEvaluation).getId();
        }else{
            return customerEvaluationRepository.deleteCustomerEvaluation(customerEvaluation.getCustomerId(),customerEvaluation.getLabel());
        }
    }

    @Override
    public int signIn(SignIn signIn) {
        return singInRepository.save(signIn).getId();
    }

    @Override
    public List<User> getUsrList() {
        return userRepository.getUsrList();
    }

    @Override
    public List<String> getCouponTotal() {
        return exchangeCouponRepository.getCouponTotal();
    }

    @Override
    public int countNum(Integer uid, Integer couponId) {
        return couponRepository.countNum(uid,couponId);
    }

    @Override
    public User getUserById(Integer id) {
        return userRepository.getOne(id);
    }

    @Override
    public List<String> getCountLabel(Integer uid) {
        return customerEvaluationRepository.getCountLabel(uid);
    }

    @Override
    public int signInVerification(Integer id,Integer type,String time) {
        return singInRepository.signInVerification(id,type,time);
    }

    @Override
    public int getIntegral(Integer type) {
        return integralRepository.getIntegral(type);
    }

    @Override
    public int signInValue(Integral integral) {
        return 0;
    }

    @Override
    public int queryUserIntegral(Integer uid) {
        return userRepository.getIntegral(uid);
    }

    @Override
    public int updateUserIntegral(User u) {
        return userRepository.updateUserJurisdiction(u);
    }

    @Override
    public int getMaxValue(Integer type) {
        return integralRepository.getMaxValue(type);
    }

    @Override
    public int sx(Integer cid) {
        return customerEvaluationRepository.sx(cid);
    }

    @Override
    public List<String> getXz(String rid, Integer cid) {
        return customerEvaluationRepository.getXz(rid,cid);
    }

    @Override
    public int deleteCustomerEvaluation(String label, Integer uid) {
        return customerEvaluationRepository.deleteCustomerEvaluationE(label,uid);
    }

    @Override
    public int getFabulousNum(String uid) {
        return receptionFabulousRepository.getFabulousNum(uid);
    }

    @Override
    public int insertReceptionFabulous(Integer cid, Integer rid) {
        return  receptionFabulousRepository.findNumByIds(cid,rid);
    }

    @Override
    public int saveReceptionFabulous(Integer cid, Integer rid) {
        ReceptionFabulous rf = new ReceptionFabulous();
        rf.setCustomerId(cid);
        rf.setReceptionId(rid);
        return receptionFabulousRepository.save(rf).getId();
    }

    @Override
    public int getFabulousType(Integer cid) {
        return receptionFabulousRepository.getFabulousType(cid);
    }

    @Override
    public int getFabulousTypes(Integer cid, String rid) {
        return receptionFabulousRepository.getFabulousTypes(cid,rid);
    }

    @Override
    public int getCountFabulous(Integer rid) {
        return customerEvaluationRepository.getCountFabulous(rid);
    }

    @Override
    public List<ExchangeCoupon> getIntegralTicket(Integer uid) {
        return exchangeCouponRepository.getIntegralTicket(uid);
    }

    @Override
    public int saveCoupon(Coupon coupon) {
        return couponRepository.save(coupon).getId();
    }

    @Override
    public int useCoupon(Integer uid, Integer couponId) {
        return tintegralRepository.useCoupon(uid,couponId);
    }

    @Override
    public int saveTintegral(Tintegral tintegral) {
        return tintegralRepository.save(tintegral).getId();
    }

    @Override
    public int getIntegralById(Integer uid) {
        return userRepository.getIntegral(uid);
    }

    @Override
    public int countPhone(String phone) {
        return 0;
    }

    @Override
    public int subordinate(SubordinateEntity subordinateEntity) {
        CustomerRegistration cr = new CustomerRegistration();
        System.out.println("分享人id===============================>"+subordinateEntity.getUid());
        cr.setReceptionId(Integer.valueOf(subordinateEntity.getUid()));
        cr.setPhone(subordinateEntity.getPhone());
        cr.setLevel("E");
        cr.setReceptionName(userRepository.findByName(Integer.valueOf(subordinateEntity.getUid())));
        cr.setCustomerSource("网络");
        cr.setComeTime(new Date());
        cr.setIsSystem(0);
        cr.setIsShow(0);
        return customerRegistrationRepository.save(cr).getId();
    }

}
